<!--
  ~ CopyRight (c) 2021 ShaoxiongDu<shaoxiongdu.dev@gmail.com>  All Rights Reserved
  -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>父访问子</title>
</head>
<body>


  <div id="app">

    <button @Click="btnClick">调用子组件的showMessage方法</button>

    <hr>

    <cpn ref="son1"/>

    <cpn ref="son2"/>

    <cpn ref="son3"/>

  </div>

  <template id="cpn">
    <div>
      <h2>子组件</h2>
    </div>
  </template>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>

  const app = new Vue({
    el: "#app",
    methods: {
      btnClick(){
        /*通过this.$children[组件下标] 访问子组件*/
        /*this.$children[0].showMessage();
        alert(this.$children[0].name)*/

        /*
        * 通过给子组件添加ref属性 然后用$.refs.<子组件ref值>取子组件的值
        * */
        console.log(this.$refs.son1.name);
      }
    },
    /*子组件*/
    components: {
      cpn: {
        template: '#cpn',
        data(){
          return {
            name: '子组件属性'
          }
        },
        methods: {
          showMessage(){
            alert("show message is run !");
          }
        }
      }
    }
  })

</script>



</body>
</html>